from PyQt5 import QtCore, QtGui, QtWidgets

from concurrent.futures import ThreadPoolExecutor
import socket
import os

from ui.home import Ui_ChatterBot
from service.socket_server import SocketServer
from service.socket_client import SocketClient
from src.Main.testModel import testByInput

class Controller(QtWidgets.QMainWindow, Ui_ChatterBot):
    def __init__(self, socket_mode=None, thread_pool=ThreadPoolExecutor(max_workers=5)):
        super().__init__()
        try:
            self.thread_pool = thread_pool
            self.socket_mode = socket_mode
            self.socket_service = None

            if self.socket_mode == 'server':
                self.thread_pool.submit(self.create_server)
            elif self.socket_mode == 'client':
                self.thread_pool.submit(self.create_client)

                self.setupUi(self)
                self.setFixedSize(440, 700)
                self.actionAbout.triggered.connect(self.actionAbout_clicked)
                # self.action.triggered.connect(QtCore.QCoreApplication.quit)
                self.action.triggered.connect(self.quit)
                self.initFun()

        except Exception as e:
            print('[error] HomeController init error:', e)


    def quit(self):
        QtCore.QTimer.singleShot(0, QtWidgets.QMainWindow.close)

    def initFun(self):
        self.pushButton.clicked.connect(self.send_msg)

    def actionAbout_clicked(self):
        QtWidgets.QMessageBox.about(self, "About", "Chatterbot by 人工智能小组")

    # 发送信息
    def send_msg(self):
        word = self.textEdit.toPlainText()
        if word == '':
            QtWidgets.QMessageBox.about(self, "提示", "发送内容不能为空！")
        else:
            self.socket_service.send_msg(word)
            self.textBrowser.append(self.socket_mode + ":\n" + word + '\n')
            self.textEdit.setText('')

    def create_client(self):
        self.socket_service = SocketClient()
        self.socket_service.start()

        while True:
            res_msg = str(self.socket_service.socket.recv(1024), encoding='utf-8')
            self.textBrowser.append("server:\n" + res_msg + '\n')
            print('[info] rec from server', res_msg)

    def create_server(self):
        self.socket_service = SocketServer()
        self.socket_service.start()

        while True:
            client, addr = self.socket_service.socket.accept()
            self.socket_service.client_list.append(client)
            self.thread_pool.submit(self.hanle_client, client, addr)

    def hanle_client(self, client, addr):
        with client:
            print('[info] conn by', addr)
            client.sendall(b'hello client!')
            while True:
                try:
                    res_msg = str(client.recv(1024), encoding='utf-8')
                    if not res_msg:
                        break
                    print("[info] rec from client:" + res_msg)
                    # self.textBrowser.append("client:\n" + res_msg + '\n')
                    temp_word = testByInput(res_msg)
                    temp_word = temp_word.encode('utf-8')
                    if not temp_word:
                        break
                    client.sendall(temp_word)

                except Exception as e:
                    print(e)
                    return
